# -*-coding:utf-8-*-
"""
@project: SM
@Time: 2024-08-01 19:54
@Author: Loneliness_Burial
@File: bank_interface.py
@Motto: 深情不改必坠死海
@software: pycharm
@version: python 3.7
"""

from db import db_handler
from conf import settings
from datetime import datetime
from lib import common

"""
银行相关的接口
"""

logger = common.get_logger('bank_logger')


# 充值
def recharge_interface(username, amount):
    user_data = db_handler.select_data(username)
    if not user_data:
        return True, f'\n用户 {username} 不存在!  '
    user_data['balance'] += amount
    msg = f'\n{datetime.now()} 用户：{username} 充值 {amount} 元，成功！\n当前余额为 {user_data.get("balance")} '
    user_data['flow'].append(msg)
    db_handler.save(user_data)
    logger.info(msg)
    return True, msg


# 提现
def withdraw_interface(username, amount):
    user_data = db_handler.select_data(username)
    balance = user_data.get('balance')
    service_fee = settings.RATE * amount
    if balance < (service_fee + amount):
        return False, '\n余额不足, 提现失败！'
    user_data['balance'] -= (amount + service_fee)
    msg = f'\n{datetime.now()} 用户：{username} 提现 {amount} 元，成功！\n手续费为 {service_fee} 元,\n当前余额为 {user_data.get("balance")} '
    user_data['flow'].append(msg)
    db_handler.save(user_data)
    logger.info(msg)
    return True, msg


# 查看余额
def check_balance_interface(username):
    user_data = db_handler.select_data(username)
    balance = user_data.get('balance')
    msg = f'用户 {username} 当前余额为：{balance} 元！'
    logger.info(msg)
    return True, msg


# 转账
def transfer_interface(username, to_username, amount):
    user_data = db_handler.select_data(username)
    to_user_data = db_handler.select_data(to_username)
    if not to_user_data:
        return True, f'\n目标用户: {to_username} 不存在！'
    if user_data.get('balance') < amount:
        return True, f'\n余额不足,转账失败！'
    user_data['balance'] -= amount
    to_user_data['balance'] += amount
    msg = f'\n{datetime.now()} 用户：{username} 给用户：{to_username} 转账 {amount} 元成功！\n当前余额为 {user_data.get("balance")} '
    user_data['flow'].append(msg)
    to_msg = f'\n{datetime.now()} 用户：{to_username} 收到用户：{username} 转账 {amount} 元成功！\n当前余额为 {to_user_data.get("balance")} '
    to_user_data['flow'].append(to_msg)
    db_handler.save(user_data)
    db_handler.save(to_user_data)
    logger.info(msg)
    return True, msg


# 查看流水
def check_flow_interface(username):
    user_data = db_handler.select_data(username)
    flow_list = user_data.get('flow')
    return True, flow_list


# 支付接口
def pay_interface(username, total):
    user_data = db_handler.select_data(username)
    if user_data.get('balance') < total:
        msg = f'用户: {username} 余额不足，支付: {total} 元失败! '
        logger.warning(msg)
        return False, msg
    user_data['balance'] -= total
    msg = f'\n{datetime.now()} 用户: {username} 消费 {total} 元，' \
          f'当前余额为: {user_data.get("balance")}'
    user_data['flow'].append(msg)
    db_handler.save(user_data)
    logger.info(msg)
    return True, msg
